package logic

import (
	"context"
	"fmt"
	"zhihu/pkg"
	"zhihu/zhihurpc/models/mysql"
	"zhihu/zhihurpc/models/redis"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatesLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatesLogic {
	return &UpdatesLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatesLogic) Updates(in *zhihurpc.UpdatesRequest) (*zhihurpc.UpdatesResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.ZhihuUser
	mysql.DB.Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	get, _ := redis.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if get != in.SendSms {
		return nil, fmt.Errorf("验证码错误")
	}

	if pkg.Md5(in.NewPassword) != pkg.Md5(in.NewPasswords) {
		return nil, fmt.Errorf("两次密码不一致")
	}
	user.Password = in.NewPasswords
	mysql.DB.Updates(&user)
	return &zhihurpc.UpdatesResponse{
		Id: int64(user.ID),
	}, nil
}
